<template>
  <div class="bind-container">
    <!-- 顶部查询按钮 -->
    <div class="query-bar">
      <el-select v-model="query.relationType" placeholder="关系类型" clearable style="width: 120px;">
        <el-option label="配偶" value="配偶" />
        <el-option label="子女" value="子女" />
        <el-option label="父母" value="父母" />
        <el-option label="其他" value="其他" />
      </el-select>
      <el-input v-model="query.realName" placeholder="家属姓名" clearable style="width: 160px;margin-left:8px;" />
      <el-button type="primary" @click="handleSearch" style="margin-left:8px;">查询</el-button>
      <el-button @click="resetQuery">重置</el-button>
    </div>

    <!-- 卡片展示区域 -->
    <div class="card-grid">
      <!-- 新建卡片 -->
      <div class="card add-card" @click="openBindDialog">
        <div class="plus-icon">+</div>
        <div class="label">新建绑定</div>
      </div>

      <!-- 已绑定老人卡片 -->
      <div
          v-for="elderly in boundElderlyList"
          :key="elderly.elderlyUserId"
          class="card elderly-card"
      >
        <img
            :src="getAvatarUrl(elderly.avatarUrl)"
            class="avatar"
            @error="handleAvatarError(elderly)"
        />
        <div class="info">
          <div class="name">{{ elderly.realName }}</div>
          <div class="relation">{{ elderly.relationType }}</div>
        </div>
        <el-button
            type="danger"
            size="small"
            @click="unbindElderly(elderly.elderlyUserId)"
        >
          取消绑定
        </el-button>
      </div>
    </div>

    <!-- 绑定弹窗 -->
    <el-dialog
        v-model="bindDialogVisible"
        title="绑定老人"
        width="600px"
        @close="resetForm"
    >
      <el-form :model="bindForm" label-width="100px">
        <el-form-item label="姓名" required>
          <el-input v-model="bindForm.realName" />
        </el-form-item>
        <el-form-item label="手机号" required>
          <el-input v-model="bindForm.phone" />
        </el-form-item>
        <el-form-item label="身份证号" required>
          <el-input v-model="bindForm.idCard" />
        </el-form-item>
        <el-form-item label="性别">
          <el-select v-model="bindForm.gender">
            <el-option label="男" :value="1" />
            <el-option label="女" :value="2" />
          </el-select>
        </el-form-item>
        <el-form-item label="出生日期">
          <el-date-picker v-model="bindForm.birthDate" type="date" />
        </el-form-item>
        <el-form-item label="关系类型" required>
          <el-select
              v-model="query.relationType"
              placeholder="请选择"
              clearable
          >
            <el-option label="配偶" value="配偶" />
            <el-option label="子女" value="子女" />
            <el-option label="其他" value="其他" />
          </el-select>
        </el-form-item>
        <el-form-item label="是否为主要联系人" label-width="150">
          <el-switch v-model="bindForm.isPrimary" :active-value="1" :inactive-value="0" />
        </el-form-item>
      </el-form>

      <template #footer>
        <el-button @click="bindDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitBind">绑定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, inject } from 'vue'
import axios from 'axios'
import { ElMessage, ElMessageBox } from 'element-plus'

const BASE_URL = 'http://localhost:8080'
const currentUser = inject('currentUser')

const boundElderlyList = ref([])
const bindDialogVisible = ref(false)
const defaultAvatar = new URL('@/assets/images/default-avatar.png', import.meta.url).href

const bindForm = ref({
  familyUserId: currentUser.value.userId,
  realName: '',
  phone: '',
  idCard: '',
  gender: null,
  birthDate: null,
  relationType: '',
  isPrimary: 0
})
// 获取头像URL（添加时间戳避免缓存）
const getAvatarUrl = (url) => {
  if (!url) return defaultAvatar;
  return `${url}?t=${Date.now()}`; // 添加时间戳确保实时加载
};

// 头像加载失败处理
const handleAvatarError = (elderly) => {
  elderly.avatarUrl = defaultAvatar; // 加载失败时回退到默认头像
};

// 查询已绑定老人
const loadBoundElderly = async () => {
  const token = localStorage.getItem('token')
  const { data } = await axios.get(
      `${BASE_URL}/api/v1/family_user/elderly/boundElderly/${currentUser.value.userId}`,
      { headers: { Authorization: `Bearer ${token}` } }
  )
  if (data.code === 2000) {
    boundElderlyList.value = data.data
  }
}

// 打开绑定弹窗
const openBindDialog = () => {
  bindDialogVisible.value = true
}

// 提交绑定
const submitBind = async () => {
  const token = localStorage.getItem('token')
  const { data } = await axios.post(
      `${BASE_URL}/api/v1/family_user/elderly/bind`,
      bindForm.value,
      { headers: { Authorization: `Bearer ${token}` } }
  )
  if (data.code === 2000) {
    ElMessage.success('绑定成功')
    bindDialogVisible.value = false
    loadBoundElderly()
  }
}

// 取消绑定
// 取消绑定
const unbindElderly = async (elderlyUserId) => {
  try {
    await ElMessageBox.confirm('确定取消绑定该老人？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })

    const token = localStorage.getItem('token')
    const { data } = await axios.post(
        `${BASE_URL}/api/v1/family_user/elderly/unbind`,
        { familyUserId: currentUser.value.userId, elderlyUserId },
        { headers: { Authorization: `Bearer ${token}` } }
    )

    if (data.code === 2000) {
      ElMessage.success('已取消绑定')
      loadBoundElderly()
    }
  } catch (e) {
    ElMessage.error(e?.response?.data?.message || '取消绑定失败')
  }
}
const query = ref({ relationType: '', realName: '' })

const handleSearch = async () => {
  const token = localStorage.getItem('token')
  const { data } = await axios.get(
      `${BASE_URL}/api/v1/family_user/elderly/boundElderly/search`,
      {
        params: {
          familyUserId: currentUser.value.userId,
          relationType: query.value.relationType,
          realName: query.value.realName
        },
        headers: { Authorization: `Bearer ${token}` }
      }
  )
  if (data.code === 2000) boundElderlyList.value = data.data
}

const resetQuery = () => {
  query.value = { relationType: '', realName: '' }
  handleSearch()
}

// 初始化加载
handleSearch()


// 初始化加载
loadBoundElderly()

// 重置表单
const resetForm = () => {
  bindForm.value = {
    familyUserId: currentUser.value.userId,
    realName: '',
    phone: '',
    idCard: '',
    gender: null,
    birthDate: null,
    relationType: '',
    isPrimary: 0
  }
}
</script>

<style scoped>
.bind-container {
  padding: 20px;
}

.top-bar {
  margin-bottom: 20px;
  text-align: right;
}

.card-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(220px, 1fr));
  gap: 20px;
}

.card {
  background: #fff;
  border-radius: 12px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
  padding: 20px;
  text-align: center;
  cursor: pointer;
  transition: all 0.3s;
}
.query-bar {
  margin-bottom: 16px;
  display: flex;
  align-items: center;
}
.add-card {
  border: 2px dashed #ccc;
  color: #999;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
}

.add-card:hover {
  border-color: #409eff;
  color: #409eff;
}

.plus-icon {
  font-size: 48px;
  font-weight: bold;
}

.label {
  margin-top: 8px;
  font-size: 14px;
}

.elderly-card {
  position: relative;
}

.avatar {
  width: 60px;
  height: 60px;
  border-radius: 50%;
  margin-bottom: 10px;
}

.name {
  font-weight: bold;
  font-size: 16px;
}

.relation {
  font-size: 14px;
  color: #666;
  margin-bottom: 10px;
}
</style>